package fun.tan90.easy.binlog.plugin.redis.single.service.impl;

import cn.hutool.json.JSONUtil;
import fun.tan90.easy.binlog.plugin.redis.common.constants.RedisPluginConstants;
import fun.tan90.easy.binlog.plugin.redis.single.model.RedisSingleParams;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/15 14:41
 */
@Slf4j
public class RedisSinglePluginService implements PluginService {

    @Override
    public boolean test(String params) {
        RedisSingleParams redisSingleParams = JSONUtil.toBean(params, RedisSingleParams.class);
        // 创建连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(redisSingleParams.getMinIdle());   // 设置最小空闲连接数
        poolConfig.setMaxIdle(redisSingleParams.getMaxIdle());   // 设置最大空闲连接数
        poolConfig.setMaxTotal(redisSingleParams.getMaxTotal()); // 设置最大连接数
        poolConfig.setMaxWait(Duration.ofMillis(redisSingleParams.getMaxWait()));   // 设置从连接池获取连接的最大等待时间

        String host = redisSingleParams.getHost();
        int port = redisSingleParams.getPort();
        int timeout = redisSingleParams.getTimeout();
        int soTimeout = RedisPluginConstants.SO_TIMEOUT;
        String user = StringUtils.hasLength(redisSingleParams.getUser()) ? redisSingleParams.getUser() : null;
        String password = StringUtils.hasLength(redisSingleParams.getPassword()) ? redisSingleParams.getPassword() : null;
        int database = redisSingleParams.getDatabase();
        try (JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout, soTimeout, user, password, database, "eb_redis")) {
            try (Jedis jedis = jedisPool.getResource()) {
                return "PONG".equals(jedis.ping());
            } catch (Exception e) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
}
